#include <LED.h>

unsigned char digits[10] = {
0x3f,	// 0	00111111 
0x06, 	// 1	00000110
0x5b, 	// 2	01011011
0x4f, 	// 3	01001111
0x66, 	// 4	01100110
0x6d, 	// 5	01101101
0x7d, 	// 6	01111101
0x07, 	// 7	00000111
0x7f, 	// 8	01111111
0x6f 	// 9	01101111
};

unsigned char letters[6] = {
0x77,	// A	01110111 
0x7c, 	// B	01111100
0x39, 	// C	00111001
0x5e, 	// D	01011110
0x79, 	// E	01111001
0x71, 	// F	01110001
};

unsigned char blank = 0x00;

volatile unsigned char segments[3] = {0,0,0};
static unsigned char counter = 0;

void InitLED()
{
	DDRC=0xff;
	PORTC=(1<<A3)|(1<<A2)|(1<<A1);
}

void SendData(unsigned char data)
{
	unsigned char i;

	for (i=0;i<8;i++)
	{
		if ((data&0x80)==0x00)
			PORTC&=~(1<<DATA);
		else 
			PORTC|=(1<<DATA);
		asm("nop");
		
		PORTC|=(1<<SHIFT);
		asm("nop");
		PORTC&=~(1<<SHIFT);
		asm("nop");

		data=data<<1;
	}

	PORTC|=(1<<LATCH);
	asm("nop");
	PORTC&=~(1<<LATCH);
}

void ConvertNum(unsigned int num)
{
	unsigned char i=0,j=0,k=0;
	
	num=num%1000;

	while (num>=100) 
	{
		num-=100; 
		k++;
	}
	while (num>=10) 
	{
		num-=10; 
		j++;
	}
	i=num;

	segments[0]=digits[i];

	if (j==0 && k==0)
		segments[1]=blank;
	else 
		segments[1]=digits[j];

	if (k==0)
		segments[2]=blank;
	else 
		segments[2]=digits[k];
}

void ConvertChar(unsigned char value)
{
	if (value==0xff)
	{
		segments[0]=blank;
	}
	else if (value>='0' && value<='9')
	{
		segments[0]=digits[value-0x30];
	}
	else if (value>='A' && value<='F')
	{
		segments[0]=letters[value-0x41];
	}
	segments[1]=blank;
	segments[2]=blank;
}

void UpdateLED()
{
	PORTC|=(1<<A3)|(1<<A2)|(1<<A1);
	SendData(~segments[counter]);
	switch(counter)
	{
		case 0:
			PORTC&=~(1<<A1);
			break;
		case 1:
			PORTC&=~(1<<A2);
			break;
		case 2:
			PORTC&=~(1<<A3);
			break;
	}
	counter=(counter+1)%3;
}
